const { signup: sign, findOne } = require('../models/users')
const { sign:tksign, compare, hash, vertify} = require("../utils/tools");


const signup = async (req, res, next) => {
    res.set('content-type', 'application/json; charset=utf-8')

    const {username, password} = req.body

    const flag = await findOne(username)
    if(flag) {
        res.render('fail', {
            data: JSON.stringify({
                flag: flag,
                msg: '用户名重复',
            })
        })
    } else {
        const msg = await sign(username, password)
        res.render('succ', {
            data: JSON.stringify(msg)
        })
    }
}

const signin = async (req, res, next) => {
    res.set('content-type', 'application/json; charset=utf-8')

    const {username, password} = req.body

    const user = await findOne(username)
    if(user && await compare(password, user.password)) {
        const tk = tksign(username)
        res.set('X-Access-Token', tk)
        res.render('succ', {
            data: JSON.stringify({
                msg: '登录成功',
                user: user
            })
        })
    } else {
        res.render('fail', {
            data: JSON.stringify('用户名或密码错误')
        })
    }
}

const userChange = async (req, res, next) => {
    res.set('content-type', 'application/json; charset=utf-8')

    let {username, password} = req.body
    let usn = req.params.username
    password = await hash(password)

    const user = await findOne(usn)

    if(user) {
        user.username = username
        user.password = password
        user.save()

        res.render('succ', {
            data: JSON.stringify('修改成功')
        })
    } else {
        res.render('fail', {
            data: JSON.stringify('错误')
        })
    }
}


module.exports = {
    signup,
    signin,
    userChange,
}